package com.ruoyi.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.domain.Vo.WXResponse;
import com.ruoyi.service.WXService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class WXServiceImpl implements WXService {
    private String APPID = "wx05b9603b56afcc60";
    private String SECRE = "46bacde99965e0b9cd40ca017bfe77f4";
    @Override
    public WXResponse getWXOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + APPID + "&secret=" + SECRE + "&js_code=" + code + "&" +
                "grant_type=authorization_code";

        OkHttpClient client = new OkHttpClient();

        // 创建一个 GET 请求
        Request request = new Request.Builder()
                .url(url) // 替换为你想要请求的 URL
                .build();

        try (Response response = client.newCall(request).execute()) {
            // 检查响应是否成功
            if (response.isSuccessful()) {
                // 打印响应体
                String result = response.body().string();
                WXResponse wxResponse = JSONObject.parseObject(result, WXResponse.class);
                return wxResponse;
            } else {
                // 处理错误情况
                log.error("获取Openid错误{}","请求失败: " + response.code());
                System.err.println("请求失败: " + response.code());
                return null;
            }
        } catch (Exception e) {
            log.error("获取Openid错误{}",e);
            e.printStackTrace();
        }
        return null;
    }
}
